package com.zhongde.cloud89app.activity;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.graphics.PathUtils;

import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate._XUpdate;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xupdate.utils.FileUtils;
import com.zhongde.cloud89app.MainActivity;
import com.zhongde.cloud89app.R;
import com.zhongde.cloud89app.utils.HProgressDialogUtils;
import com.zhongde.cloud89app.utils.MyPreference;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import okhttp3.Call;


import static com.zhongde.cloud89app.base.Configuration.API_TOKEN;
import static com.zhongde.cloud89app.base.Configuration.APP_ID;
import static com.zhongde.cloud89app.base.Configuration.BASE_URL;


public class LoginActivity extends AppCompatActivity {
    MyPreference pref;
    TextView editTextTextPersonName, editTextTextPassword;
    Button btn_login, btn_reg;
    LoadingDailog dialog;
    ImageView login_image;
    Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        editTextTextPersonName = findViewById(R.id.editTextTextPersonName);
        editTextTextPassword = findViewById(R.id.editTextTextPassword);
        btn_login = findViewById(R.id.btn_login);
        login_image = findViewById(R.id.login_image);
        btn_reg = findViewById(R.id.btn_reg);
        initView();
        checkUpdata();

    }

    private void initView() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        pref = new MyPreference(LoginActivity.this);
        editTextTextPersonName.setText(pref.getString("userName"));
        editTextTextPassword.setText(pref.getString("password"));
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(this)
                .setMessage("登录中...")
                .setCancelable(false)
                .setCancelOutside(false);
        dialog = loadBuilder.create();

        btn_reg.setOnClickListener(v -> {

            startActivity(new Intent(this, RegActivity.class));

        });


        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String uname = editTextTextPersonName.getText().toString().trim();
                String pwd = editTextTextPassword.getText().toString();
                if (uname == null) {
                    Toast.makeText(LoginActivity.this, "用户名不可为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (pwd == null) {
                    Toast.makeText(LoginActivity.this, "密码名不可为空", Toast.LENGTH_SHORT).show();
                    return;
                }


                dialog.show();
                OkHttpUtils
                        .post()
                        .url(BASE_URL + "Z_a_user_msg_Controller/Verify_the_login.do")
                        .addParams("username", uname)
                        .addParams("password", pwd)
                        .addParams("Remember_the_password_check_box", "1")
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);

                                    Toast.makeText(LoginActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                    if (jsonObject.getInt("code") != 0) {

                                        //code
                                        // 0 登录失败
                                        // 1 主账号登录
                                        // 2 子账号登录
                                        pref.putIntAndCommit("userleve", jsonObject.getInt("code"));
                                        pref.putStringAndCommit("userName", uname);
                                        pref.putStringAndCommit("password", pwd);
                                        pref.putStringAndCommit("describe", jsonObject.getJSONObject("data").getString("describe"));

                                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                        startActivity(intent, ActivityOptionsCompat
                                                .makeSceneTransitionAnimation(LoginActivity.this, login_image, "zhongde_image").toBundle());

                                        mHandler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                finish();
                                            }
                                        }, 2000);

                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onAfter(int id) {
                                super.onAfter(id);
                                dialog.hide();
                            }
                        });

            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        dialog.dismiss();
    }

    //检查更新
    private void checkUpdata() {

        OkHttpUtils
                .get()
                .url("http://api.bq04.com/apps/latest/" + APP_ID)
                .addParams("api_token", API_TOKEN)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int v = jsonObject.getInt("version");
                            if (v > getVersionCode()) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                                builder.setTitle("更新");        //设置弹出窗口的标题
                                builder.setMessage("有新版本app，建议更新");
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    //设定PositiveButton
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        try {
                                            downloadFile(jsonObject.getString("installUrl"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                                builder.setNeutralButton("取消", null);
                                builder.show();


                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                    }
                });

    }

    private void downloadFile(String installUrl) {
        XUpdate.newBuild(LoginActivity.this)
                .build()
                .download(installUrl, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                    @Override
                    public void onStart() {
                        HProgressDialogUtils.showHorizontalProgressDialog(LoginActivity.this, "下载进度", false);
                    }

                    @Override
                    public void onProgress(float progress, long total) {
                        HProgressDialogUtils.setProgress(Math.round(progress * 100));
                    }

                    @Override
                    public boolean onCompleted(File file) {
                        HProgressDialogUtils.cancel();
                        _XUpdate.startInstallApk(LoginActivity.this, file); //填写文件所在的路径
                        return false;
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        HProgressDialogUtils.cancel();
                    }
                });


    }

    private int getVersionCode() {
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    private long exitTime = 0;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再次返回退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                android.os.Process.killProcess(android.os.Process.myPid()); //获取PID
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}